module ActionView
  module Helpers
    module UrlHelper
      alias_method :rails_link_to, :link_to
    
      def link_to(name, options = {}, html_options = nil)
        url = lock_down_url(options, html_options)
        if authorized? url
          return rails_link_to(name,options,html_options)
        end
        return ""
      end

			def link_to_or_show(name, options = {}, html_options = nil)
				lnk = link_to(name, options, html_options)
				lnk.blank? ? name : lnk
      end

      alias_method :rails_button_to, :button_to
    
      def button_to(name, options = {}, html_options = nil)
        url = lock_down_url(options, html_options)
        if authorized? url
          return rails_button_to(name,options,html_options)
        end
        return ""
      end
      
      def links(*lis)
        rvalue = []
        lis.each{|link| rvalue << link if link.length > 0 }
        rvalue.join(" | ")
      end
    
      private
        def lock_down_url(options, html_options = {})
          return options unless options.respond_to?(:new_record?)
          p = polymorphic_path(options)
          if html_options.is_a?(Hash) && html_options[:method] == :delete
            return p + "/destroy"
          end
          
          return p + "/show" if p.split("/").last.to_i > 0
          #pass on to authorized? methods 
          return options
        end
    end
  end
end
